import Nodemailer from 'nodemailer';
import logger from '../Logger/logger';

/**
 * 需要在根目录下创建.env.dev文件，内容如下：
 * MAILER_USER=QQ发件邮箱
 * MAILER_PASS=QQ发件邮箱授权码
 * */
require('dotenv').config();
const config = {
  host: 'smtp.qq.com',
  port: 465,
  secureConnection: true,
  service: 'qq',
  auth: {
    user: process.env.MAILER_USER,    //发件账号
    pass: process.env.MAILER_PASS    //发件邮箱授权码
  }
};

export const smtp = {
  getHost() {
    return config.host;
  },
  getUser() {
    return config.auth.user;
  }
};

const transport = Nodemailer.createTransport(config);

export const sendMail = async (from: string, to: string, subject: string, html: string) => {
  await transport.sendMail({
    from: from, // 设置发件人名称
    to: to,  //接收者邮箱
    subject: subject, //主题
    html: html //内容
  }, (err, info) => {
    if (err) {
      logger.error(err.toString());
      return;
    }
    logger.info(`Message sent: ${info.messageId}`);
  });
};

